<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title>JS分页</title>
		<link rel="stylesheet" href="css/bootstrap.min.css" />
		<script src="js/jquery-3.2.1.min.js"></script>
	</head>

	<body>

		<nav aria-label="Page navigation">
			<ul class="pagination">

			</ul>
		</nav>

		<script>
			function Pages() {
				var total = 100; //总记录数	- 从后台读取
				var pageSize = 9; //每页几个 ,12
				var navSize = 5; //导航显示几个
				var pageCount = Math.ceil(total / pageSize);
				var currentPage = getCurrentPage();
				var next = "";
				var pre = "";
				var str = "";

				// ?currentpage=1
				//获取当前页
				function getCurrentPage() {
					if(!location.search) {
						return 1;
					} else {
						var search = location.search;
						var ptn = /currentpage=([0-9]+)/;
						var rs = search.match(ptn);
						if(rs) {
							if(rs[1] >= pageCount) {
								return pageCount;
							}
							return parseInt(rs[1]);
						} else {
							return 1;
						}
					}

				}

				//上一页
				function prev() {
					if((prePage = (currentPage - 1)) >= 1) {
						pre = '<li><a href="?currentpage=' + prePage + '"  aria-label="Previous"><span aria-hidden="true">&laquo;</span></a></li>';
					} else {
						pre = "";
					}
				}

				prev();

				//下一页
				function fNext() {
					if((nextPage = (currentPage + 1)) <= pageCount) {
						next = '<li><a href="?currentpage=' + nextPage + '"  aria-label="Next"><span aria-hidden="true">&raquo;</span></a></li>';
					} else {
						next = "";
					}
				}
				fNext();

				str += pre;
				if(currentPage < navSize / 2) {
					for(var i = 1; i < 6; i++) {
						cls = (i == currentPage) ? ' class="active" ' : "";
						str += '<li ' + cls + '><a href="?currentpage=' + i + '">' + i + '</a></li>';
					}
				} else {
					//已知中间，求两边。
					// 3,4,5,6,7
					if(currentPage <= pageCount - 3) {
						for(var i = currentPage - 2; i < currentPage + 3; i++) {
							cls = (i == currentPage) ? ' class="active" ' : "";
							str += '<li' + cls + '><a href="?currentpage=' + i + '">' + i + '</a></li>';
						}
					} else {
						for(var i = pageCount - 4; i <= pageCount; i++) {
							cls = (i == currentPage) ? ' class="active" ' : "";
							str += '<li' + cls + '><a href="?currentpage=' + i + '">' + i + '</a></li>';
						}
					}

				}
				str += next;

				return str;
			}

			$(".pagination").html(Pages())

			//总记录数 - 100个，
			//设定每页：几个- 9
			//求页数：Math.ceil(100/9)  12页  
			//每次显示多少？ 5个
			//上一页，下一页
			//如果已经是第一页，不显示上一页。如果已经是最后一页不应该显示下一页。

			// perpage , pages 

			//数据库逻辑
			/*		SELECT count(*) FROM products ;
					
					SELECT * FROM products limit 0,9 ;
					
					SELECT * FROM products limit 10,17 ;
					
					SELECT * FROM products limit 18,26 ;
					*/
		</script>
	</body>

</html>